package com.ontheroad.mysql.leanCloud.listener;

import com.ontheroad.activity.model.ActivityModel;
import com.ontheroad.activity.service.ActivitService;
import com.ontheroad.leanCloud.event.CreateSessionEvent;
import com.ontheroad.leanCloud.model.PushType;
import com.ontheroad.leanCloud.service.LeanCloudService;
import com.ontheroad.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by kedong on 2017/11/14 0014.
 */
@Service
public class CreateSessionListener implements ApplicationListener<CreateSessionEvent> {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private LeanCloudService leanCloudService;
    @Autowired
    private ActivitService activitService;
    @Autowired
    private UserService userService;

    @Override
    public void onApplicationEvent(CreateSessionEvent event) {
        try {
            String objectId = leanCloudService.createSession(event.getSessionName(), event.getJson(), event.getUserIds());
            if (objectId != null) {
                /**
                 * 即实时通信中的对话 ID，客户端就可以通过这个 ID 发送消息了
                 */
                if (StringUtils.isNotBlank(objectId)) {
                    switch (event.getType()) {
                        case ACTIVITY:
                            activity(event.getId(), objectId);
                    }
                }
            }
        } catch (Exception e) {
            log.error("创建会话失败", e);
        }
    }

    /**
     * 更新活动的会话ID
     *
     * @param id
     * @param objectId
     */
    private void activity(Integer id, String objectId) {
        ActivityModel model = activitService.findById(id);
        model.setObjectId(objectId);
        activitService.updateById(model);
        try {
            // TODO 推送
            Map<String, Object> map = new HashMap<>();
            map.put("action", PushType.ACTIVITY.getValue());
            map.put("id", model.getId());
            leanCloudService.push(model.getTitle(), null, map);
        } catch (Exception e) {
            log.error("推送失败", e);
        }
    }
}
